﻿Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Collections
Imports System.IO
Imports FileNet.Api
Imports FileNet.Api.Core
Imports FileNet.Api.Collection
Imports FileNet.Api.Util
Imports FileNet.Api.Constants
Imports FileNet.Api.Query
Imports FileNet.Api.Property
Imports Microsoft.Web.Services3.Security.Tokens
Imports System.ComponentModel
Imports System.Drawing
Imports System.Drawing.Imaging

''' <summary>
''' 提供操作 FileNet Content Engine 的共用元件及方法
''' </summary>
''' <remarks></remarks>
Public Class clsUtil

    Private oLog As LogHandler.clsLogger
    Private mTraceFlag As Boolean = True
    Private mLogFolder As String = ""
    Private mTraceLogPrefix As String = ""
    Private mCacheFolder As String = ""
    Private mCleanCache As Boolean = False

    Private isConnected As Boolean
    Private domain As IDomain
    Private domainName As String
    Private ost As IObjectStoreSet
    Private connection As IConnection
    Private oCredentials As Authentication.UsernameCredentials

#Region "Structure Definition"

    ''' <summary>
    ''' CE Connection 的相關資訊資料結構
    ''' </summary>
    ''' <remarks></remarks>
    Public Structure CEConnection
        Dim conn As FileNet.Api.Core.IConnection
        Dim domain As FileNet.Api.Core.IDomain
        Dim objectStores As FileNet.Api.Collection.IObjectStoreSet
        Dim domainName As String
        Dim aryObjectStoreName As ArrayList

    End Structure

    ''' <summary>
    ''' 定義屬性的資料結構
    ''' </summary>
    ''' <remarks></remarks>
    Public Structure PropertyInfo
        <Description("屬性名稱")> Dim PropertyName As String
        <Description("屬性值")> Dim PropertyValue As Object
    End Structure

#End Region

#Region " properties Definition "

    ''' <summary>
    ''' 取得所有的 ObjectStore
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public ReadOnly Property ObjectStores() As FileNet.Api.Collection.IObjectStoreSet
        Get
            Try
                Return domain.ObjectStores
            Catch ex As Exception
                oLog.writeLine(mLogFolder, "ej", ex.ToString)
                Throw New Exception(ex.ToString)
            End Try
        End Get
    End Property

    ''' <summary>
    ''' 傳入 Object Store Name 回傳登入後的 對應的 Object Store 
    ''' </summary>
    ''' <param name="sObjectStoreName"></param>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public ReadOnly Property ObjectStore(ByVal sObjectStoreName As String) As IObjectStore
        Get
            Return FetchObjectStore(sObjectStoreName)
        End Get
    End Property

    ''' <summary>
    ''' 設定是否要記錄追蹤紀錄
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property TraceLog() As Boolean
        Get
            Return mTraceFlag
        End Get
        Set(ByVal value As Boolean)
            mTraceFlag = value
        End Set
    End Property

    ''' <summary>
    ''' 設定/取出 文件所暫存的位置 Ex: "c:\cache\"
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property CacheFolder() As String
        Get
            Return mCacheFolder
        End Get
        Set(ByVal value As String)
            If System.IO.Directory.Exists(value) Then
                mCacheFolder = value.Trim("\") & "\"
            Else
                System.IO.Directory.CreateDirectory(value)
                mCacheFolder = value.Trim("\") & "\"
            End If
        End Set
    End Property

#End Region

#Region "Enum"
    ''' <summary>
    ''' 定義 MimeType 的列舉
    ''' </summary>
    ''' <remarks></remarks>
    Public Enum MimeType
        <Description("x-world/x-3dmf;.3dm")> x_world_x_3dmf = 2
        <Description("application/octet-stream;.a")> application_octet_stream = 4
        <Description("application/x-authorware-bin;.aab")> application_x_authorware_bin = 5
        <Description("application/x-authorware-map;.aam")> application_x_authorware_map = 6
        <Description("application/x-authorware-seg;.aas")> application_x_authorware_seg = 7
        <Description("text/vnd.abc;.abc")> text_vnd_abc = 8
        <Description("text/html;.acgi")> text_html = 9
        <Description("video/animaflex;.afl")> video_animaflex = 10
        <Description("application/postscript;.ai")> application_postscript = 11
        <Description("audio/aiff;.aif")> audio_aiff = 12
        <Description("audio/x-aiff;.aif")> audio_x_aiff = 13
        <Description("application/x-aim;.aim")> application_x_aim = 18
        <Description("text/x-audiosoft-intra;.aip")> text_x_audiosoft_intra = 19
        <Description("application/x-navi-animation;.ani")> application_x_navi_animation = 20
        <Description("application/x-nokia-9000-communicator-add-on-software;.aos")> application_x_nokia_9000_communicator_add_on_software = 21
        <Description("application/mime;.aps")> application_mime = 22
        <Description("application/arj;.arj")> application_arj = 24
        <Description("image/x-jg;.art")> image_x_jg = 26
        <Description("video/x-ms-asf;.asf")> video_x_ms_asf = 27
        <Description("text/x-asm;.asm")> text_x_asm = 28
        <Description("text/asp;.asp")> text_asp = 29
        <Description("application/x-mplayer2;.asx")> application_x_mplayer2 = 30
        <Description("video/x-ms-asf-plugin;.asx")> video_x_ms_asf_plugin = 32
        <Description("audio/basic;.au")> audio_basic = 33
        <Description("audio/x-au;.au")> audio_x_au = 34
        <Description("application/x-troff-msvideo;.avi")> application_x_troff_msvideo = 35
        <Description("video/avi;.avi")> video_avi = 36
        <Description("video/msvideo;.avi")> video_msvideo = 37
        <Description("video/x-msvideo;.avi")> video_x_msvideo = 38
        <Description("video/avs-video;.avs")> video_avs_video = 39
        <Description("application/x-bcpio;.bcpio")> application_x_bcpio = 40
        <Description("application/mac-binary;.bin")> application_mac_binary = 41
        <Description("application/macbinary;.bin")> application_macbinary = 42
        <Description("application/x-binary;.bin")> application_x_binary = 44
        <Description("application/x-macbinary;.bin")> application_x_macbinary = 45
        <Description("image/bmp;.bm")> image_bmp = 46
        <Description("image/x-windows-bmp;.bmp")> image_x_windows_bmp = 48
        <Description("application/book;.boo")> application_book = 49
        <Description("application/x-bzip2;.boz")> application_x_bzip2 = 51
        <Description("application/x-bsh;.bsh")> application_x_bsh = 52
        <Description("application/x-bzip;.bz")> application_x_bzip = 53
        <Description("text/plain;.c")> text_plain = 55
        <Description("text/x-c;.c")> text_x_c = 56
        <Description("application/vnd.ms-pki.seccat;.cat")> application_vnd_ms_pki_seccat = 58
        <Description("application/clariscad;.ccad")> application_clariscad = 61
        <Description("application/x-cocoa;.cco")> application_x_cocoa = 62
        <Description("application/cdf;.cdf")> application_cdf = 63
        <Description("application/x-cdf;.cdf")> application_x_cdf = 64
        <Description("application/x-netcdf;.cdf")> application_x_netcdf = 65
        <Description("application/pkix-cert;.cer")> application_pkix_cert = 66
        <Description("application/x-x509-ca-cert;.cer")> application_x_x509_ca_cert = 67
        <Description("application/x-chat;.cha")> application_x_chat = 68
        <Description("application/java;.class")> application_java = 70
        <Description("application/java-byte-code;.class")> application_java_byte_code = 71
        <Description("application/x-java-class;.class")> application_x_java_class = 72
        <Description("application/x-cpio;.cpio")> application_x_cpio = 76
        <Description("application/mac-compactpro;.cpt")> application_mac_compactpro = 78
        <Description("application/x-compactpro;.cpt")> application_x_compactpro = 79
        <Description("application/x-cpt;.cpt")> application_x_cpt = 80
        <Description("application/pkcs-crl;.crl")> application_pkcs_crl = 81
        <Description("application/pkix-crl;.crl")> application_pkix_crl = 82
        <Description("application/x-x509-user-cert;.crt")> application_x_x509_user_cert = 85
        <Description("application/x-csh;.csh")> application_x_csh = 86
        <Description("text/x-script.csh;.csh")> text_x_script_csh = 87
        <Description("application/x-pointplus;.css")> application_x_pointplus = 88
        <Description("text/css;.css")> text_css = 89
        <Description("application/x-director;.dcr")> application_x_director = 91
        <Description("application/x-deepv;.deepv")> application_x_deepv = 92
        <Description("video/x-dv;.dif")> video_x_dv = 95
        <Description("video/dl;.dl")> video_dl = 97
        <Description("video/x-dl;.dl")> video_x_dl = 98
        <Description("application/msword;.doc")> application_msword = 99
        <Description("application/commonground;.dp")> application_commonground = 101
        <Description("application/drafting;.drw")> application_drafting = 102
        <Description("application/x-dvi;.dvi")> application_x_dvi = 105
        <Description("drawing/x-dwf (old);.dwf")> drawing_x_dwf = 106
        <Description("model/vnd.dwf;.dwf")> model_vnd_dwf = 107
        <Description("application/acad;.dwg")> application_acad = 108
        <Description("image/vnd.dwg;.dwg")> image_vnd_dwg = 109
        <Description("image/x-dwg;.dwg")> image_x_dwg = 110
        <Description("application/dxf;.dxf")> application_dxf = 111
        <Description("text/x-script.elisp;.el")> text_x_script_elisp = 115
        <Description("application/x-bytecode.elisp (compiled elisp);.elc")> application_x_bytecode_elisp = 116
        <Description("application/x-elc;.elc")> application_x_elc = 117
        <Description("application/x-envoy;.env")> application_x_envoy = 118
        <Description("application/x-esrehber;.es")> application_x_esrehber = 120
        <Description("text/x-setext;.etx")> text_x_setext = 121
        <Description("application/envoy;.evy")> application_envoy = 122
        <Description("text/x-fortran;.f")> text_x_fortran = 126
        <Description("application/vnd.fdf;.fdf")> application_vnd_fdf = 130
        <Description("application/fractals;.fif")> application_fractals = 131
        <Description("image/fif;.fif")> image_fif = 132
        <Description("video/fli;.fli")> video_fli = 133
        <Description("video/x-fli;.fli")> video_x_fli = 134
        <Description("image/florian;.flo")> image_florian = 135
        <Description("text/vnd.fmi.flexstor;.flx")> text_vnd_fmi_flexstor = 136
        <Description("video/x-atomic3d-feature;.fmf")> video_x_atomic3d_feature = 137
        <Description("image/vnd.fpx;.fpx")> image_vnd_fpx = 140
        <Description("image/vnd.net-fpx;.fpx")> image_vnd_net_fpx = 141
        <Description("application/freeloader;.frl")> application_freeloader = 142
        <Description("audio/make;.funk")> audio_make = 143
        <Description("image/g3fax;.g3")> image_g3fax = 145
        <Description("image/gif;.gif")> image_gif = 146
        <Description("video/gl;.gl")> video_gl = 147
        <Description("video/x-gl;.gl")> video_x_gl = 148
        <Description("audio/x-gsm;.gsd")> audio_x_gsm = 149
        <Description("application/x-gsp;.gsp")> application_x_gsp = 151
        <Description("application/x-gss;.gss")> application_x_gss = 152
        <Description("application/x-gtar;.gtar")> application_x_gtar = 153
        <Description("application/x-compressed;.gz")> application_x_compressed = 154
        <Description("application/x-gzip;.gz")> application_x_gzip = 155
        <Description("multipart/x-gzip;.gzip")> multipart_x_gzip = 157
        <Description("text/x-h;.h")> text_x_h = 159
        <Description("application/x-hdf;.hdf")> application_x_hdf = 160
        <Description("application/x-helpfile;.help")> application_x_helpfile = 161
        <Description("application/vnd.hp-hpgl;.hgl")> application_vnd_hp_hpgl = 162
        <Description("text/x-script;.hlb")> text_x_script = 165
        <Description("application/hlp;.hlp")> application_hlp = 166
        <Description("application/x-winhelp;.hlp")> application_x_winhelp = 168
        <Description("application/binhex;.hqx")> application_binhex = 171
        <Description("application/binhex4;.hqx")> application_binhex4 = 172
        <Description("application/mac-binhex;.hqx")> application_mac_binhex = 173
        <Description("application/mac-binhex40;.hqx")> application_mac_binhex40 = 174
        <Description("application/x-binhex40;.hqx")> application_x_binhex40 = 175
        <Description("application/x-mac-binhex40;.hqx")> application_x_mac_binhex40 = 176
        <Description("application/hta;.hta")> application_hta = 177
        <Description("text/x-component;.htc")> text_x_component = 178
        <Description("text/webviewhtml;.htt")> text_webviewhtml = 182
        <Description("x-conference/x-cooltalk;.ice")> x_conference_x_cooltalk = 184
        <Description("image/x-icon;.ico")> image_x_icon = 185
        <Description("image/ief;.ief")> image_ief = 187
        <Description("application/iges;.iges")> application_iges = 189
        <Description("model/iges;.iges")> model_iges = 190
        <Description("application/x-ima;.ima")> application_x_ima = 193
        <Description("application/x-httpd-imap;.imap")> application_x_httpd_imap = 194
        <Description("application/inf;.inf")> application_inf = 195
        <Description("application/x-internett-signup;.ins")> application_x_internett_signup = 196
        <Description("application/x-ip2;.ip")> application_x_ip2 = 197
        <Description("video/x-isvideo;.isu")> video_x_isvideo = 198
        <Description("audio/it;.it")> audio_it = 199
        <Description("application/x-inventor;.iv")> application_x_inventor = 200
        <Description("i-world/i-vrml;.ivr")> i_world_i_vrml = 201
        <Description("application/x-livescreen;.ivy")> application_x_livescreen = 202
        <Description("audio/x-jam;.jam")> audio_x_jam = 203
        <Description("text/x-java-source;.jav")> text_x_java_source = 205
        <Description("application/x-java-commerce;.jcm")> application_x_java_commerce = 208
        <Description("image/jpeg;.jpg")> image_jpeg = 209
        <Description("image/pjpeg;.jfif")> image_pjpeg = 210
        <Description("image/x-jps;.jps")> image_x_jps = 218
        <Description("application/x-javascript;.js")> application_x_javascript = 219
        <Description("image/jutvision;.jut")> image_jutvision = 220
        <Description("audio/midi;.kar")> audio_midi = 221
        <Description("music/x-karaoke;.kar")> music_x_karaoke = 222
        <Description("application/x-ksh;.ksh")> application_x_ksh = 223
        <Description("text/x-script.ksh;.ksh")> text_x_script_ksh = 224
        <Description("audio/nspaudio;.la")> audio_nspaudio = 225
        <Description("audio/x-nspaudio;.la")> audio_x_nspaudio = 226
        <Description("audio/x-liveaudio;.lam")> audio_x_liveaudio = 227
        <Description("application/x-latex;.latex")> application_x_latex = 228
        <Description("application/lha;.lha")> application_lha = 229
        <Description("application/x-lha;.lha")> application_x_lha = 231
        <Description("application/x-lisp;.lsp")> application_x_lisp = 237
        <Description("text/x-script.lisp;.lsp")> text_x_script_lisp = 238
        <Description("text/x-la-asf;.lsx")> text_x_la_asf = 240
        <Description("application/x-lzh;.lzh")> application_x_lzh = 243
        <Description("application/lzx;.lzx")> application_lzx = 244
        <Description("application/x-lzx;.lzx")> application_x_lzx = 246
        <Description("text/x-m;.m")> text_x_m = 248
        <Description("video/mpeg;.m1v")> video_mpeg = 249
        <Description("audio/mpeg;.m2a")> audio_mpeg = 250
        <Description("audio/x-mpequrl;.m3u")> audio_x_mpequrl = 252
        <Description("application/x-troff-man;.man")> application_x_troff_man = 253
        <Description("application/x-navimap;.map")> application_x_navimap = 254
        <Description("application/mbedlet;.mbd")> application_mbedlet = 256
        <Description("application/x-magic-cap-package-1.0;.mc$")> application_x_magic_cap_package_1_0 = 257
        <Description("application/mcad;.mcd")> application_mcad = 258
        <Description("application/x-mathcad;.mcd")> application_x_mathcad = 259
        <Description("image/vasa;.mcf")> image_vasa = 260
        <Description("text/mcf;.mcf")> text_mcf = 261
        <Description("application/netmc;.mcp")> application_netmc = 262
        <Description("application/x-troff-me;.me")> application_x_troff_me = 263
        <Description("message/rfc822;.mht")> message_rfc822 = 264
        <Description("application/x-midi;.mid")> application_x_midi = 266
        <Description("audio/x-mid;.mid")> audio_x_mid = 268
        <Description("audio/x-midi;.mid")> audio_x_midi = 269
        <Description("music/crescendo;.mid")> music_crescendo = 270
        <Description("x-music/x-midi;.mid")> x_music_x_midi = 271
        <Description("application/x-frame;.mif")> application_x_frame = 278
        <Description("application/x-mif;.mif")> application_x_mif = 279
        <Description("www/mime;.mime")> www_mime = 281
        <Description("audio/x-vnd.audioexplosion.mjuicemediafile;.mjf")> audio_x_vnd_audioexplosion_mjuicemediafile = 282
        <Description("video/x-motion-jpeg;.mjpg")> video_x_motion_jpeg = 283
        <Description("application/base64;.mm")> application_base64 = 284
        <Description("application/x-meme;.mm")> application_x_meme = 285
        <Description("audio/mod;.mod")> audio_mod = 287
        <Description("audio/x-mod;.mod")> audio_x_mod = 288
        <Description("video/quicktime;.moov")> video_quicktime = 289
        <Description("video/x-sgi-movie;.movie")> video_x_sgi_movie = 291
        <Description("audio/x-mpeg;.mp2")> audio_x_mpeg = 293
        <Description("video/x-mpeg;.mp2")> video_x_mpeg = 295
        <Description("video/x-mpeq2a;.mp2")> video_x_mpeq2a = 296
        <Description("audio/mpeg3;.mp3")> audio_mpeg3 = 297
        <Description("audio/x-mpeg-3;.mp3")> audio_x_mpeg_3 = 298
        <Description("application/x-project;.mpc")> application_x_project = 303
        <Description("application/vnd.ms-project;.mpp")> application_vnd_ms_project = 309
        <Description("application/marc;.mrc")> application_marc = 313
        <Description("application/x-troff-ms;.ms")> application_x_troff_ms = 314
        <Description("application/x-vnd.audioexplosion.mzz;.mzz")> application_x_vnd_audioexplosion_mzz = 317
        <Description("image/naplps;.nap")> image_naplps = 318
        <Description("application/vnd.nokia.configuration-message;.ncm")> application_vnd_nokia_configuration_message = 321
        <Description("image/x-niff;.nif")> image_x_niff = 322
        <Description("application/x-mix-transfer;.nix")> application_x_mix_transfer = 324
        <Description("application/x-conference;.nsc")> application_x_conference = 325
        <Description("application/x-navidoc;.nvd")> application_x_navidoc = 326
        <Description("application/oda;.oda")> application_oda = 328
        <Description("application/x-omc;.omc")> application_x_omc = 329
        <Description("application/x-omcdatamaker;.omcd")> application_x_omcdatamaker = 330
        <Description("application/x-omcregerator;.omcr")> application_x_omcregerator = 331
        <Description("text/x-pascal;.p")> text_x_pascal = 332
        <Description("application/pkcs10;.p10")> application_pkcs10 = 333
        <Description("application/x-pkcs10;.p10")> application_x_pkcs10 = 334
        <Description("application/pkcs-12;.p12")> application_pkcs_12 = 335
        <Description("application/x-pkcs12;.p12")> application_x_pkcs12 = 336
        <Description("application/x-pkcs7-signature;.p7a")> application_x_pkcs7_signature = 337
        <Description("application/pkcs7-mime;.p7c")> application_pkcs7_mime = 338
        <Description("application/x-pkcs7-mime;.p7c")> application_x_pkcs7_mime = 339
        <Description("application/x-pkcs7-certreqresp;.p7r")> application_x_pkcs7_certreqresp = 342
        <Description("application/pkcs7-signature;.p7s")> application_pkcs7_signature = 343
        <Description("application/pro_eng;.part")> application_pro_eng = 344
        <Description("text/pascal;.pas")> text_pascal = 345
        <Description("image/x-portable-bitmap;.pbm")> image_x_portable_bitmap = 346
        <Description("application/vnd.hp-pcl;.pcl")> application_vnd_hp_pcl = 347
        <Description("application/x-pcl;.pcl")> application_x_pcl = 348
        <Description("image/x-pict;.pct")> image_x_pict = 349
        <Description("image/x-pcx;.pcx")> image_x_pcx = 350
        <Description("chemical/x-pdb;.pdb")> chemical_x_pdb = 351
        <Description("application/pdf;.pdf")> application_pdf = 352
        <Description("audio/make.my.funk;.pfunk")> audio_make_my_funk = 354
        <Description("image/x-portable-graymap;.pgm")> image_x_portable_graymap = 355
        <Description("image/x-portable-greymap;.pgm")> image_x_portable_greymap = 356
        <Description("image/pict;.pic")> image_pict = 357
        <Description("application/x-newton-compatible-pkg;.pkg")> application_x_newton_compatible_pkg = 359
        <Description("application/vnd.ms-pki.pko;.pko")> application_vnd_ms_pki_pko = 360
        <Description("text/x-script.perl;.pl")> text_x_script_perl = 362
        <Description("application/x-pixclscript;.plx")> application_x_pixclscript = 363
        <Description("image/x-xpixmap;.pm")> image_x_xpixmap = 364
        <Description("text/x-script.perl-module;.pm")> text_x_script_perl_module = 365
        <Description("application/x-pagemaker;.pm4")> application_x_pagemaker = 366
        <Description("image/png;.png")> image_png = 368
        <Description("application/x-portable-anymap;.pnm")> application_x_portable_anymap = 369
        <Description("image/x-portable-anymap;.pnm")> image_x_portable_anymap = 370
        <Description("application/mspowerpoint;.pot")> application_mspowerpoint = 371
        <Description("application/vnd.ms-powerpoint;.pot")> application_vnd_ms_powerpoint = 372
        <Description("model/x-pov;.pov")> model_x_pov = 373
        <Description("image/x-portable-pixmap;.ppm")> image_x_portable_pixmap = 375
        <Description("application/powerpoint;.ppt")> application_powerpoint = 379
        <Description("application/x-mspowerpoint;.ppt")> application_x_mspowerpoint = 381
        <Description("application/x-freelance;.pre")> application_x_freelance = 383
        <Description("paleovu/x-pv;.pvu")> paleovu_x_pv = 387
        <Description("text/x-script.phyton;.py")> text_x_script_phyton = 389
        <Description("applicaiton/x-bytecode.python;.pyc")> applicaiton_x_bytecode_python = 390
        <Description("audio/vnd.qcelp;.qcp")> audio_vnd_qcelp = 391
        <Description("image/x-quicktime;.qif")> image_x_quicktime = 394
        <Description("video/x-qtc;.qtc")> video_x_qtc = 396
        <Description("audio/x-pn-realaudio;.ra")> audio_x_pn_realaudio = 399
        <Description("audio/x-pn-realaudio-plugin;.ra")> audio_x_pn_realaudio_plugin = 400
        <Description("audio/x-realaudio;.ra")> audio_x_realaudio = 401
        <Description("application/x-cmu-raster;.ras")> application_x_cmu_raster = 403
        <Description("image/cmu-raster;.ras")> image_cmu_raster = 404
        <Description("image/x-cmu-raster;.ras")> image_x_cmu_raster = 405
        <Description("text/x-script.rexx;.rexx")> text_x_script_rexx = 407
        <Description("image/vnd.rn-realflash;.rf")> image_vnd_rn_realflash = 408
        <Description("image/x-rgb;.rgb")> image_x_rgb = 409
        <Description("application/vnd.rn-realmedia;.rm")> application_vnd_rn_realmedia = 410
        <Description("audio/mid;.rmi")> audio_mid = 412
        <Description("application/ringing-tones;.rng")> application_ringing_tones = 416
        <Description("application/vnd.nokia.ringing-tone;.rng")> application_vnd_nokia_ringing_tone = 417
        <Description("application/vnd.rn-realplayer;.rnx")> application_vnd_rn_realplayer = 418
        <Description("application/x-troff;.roff")> application_x_troff = 419
        <Description("image/vnd.rn-realpix;.rp")> image_vnd_rn_realpix = 420
        <Description("text/richtext;.rt")> text_richtext = 422
        <Description("text/vnd.rn-realtext;.rt")> text_vnd_rn_realtext = 423
        <Description("application/rtf;.rtf")> application_rtf = 424
        <Description("application/x-rtf;.rtf")> application_x_rtf = 425
        <Description("video/vnd.rn-realvideo;.rv")> video_vnd_rn_realvideo = 429
        <Description("audio/s3m;.s3m")> audio_s3m = 431
        <Description("application/x-tbook;.sbk")> application_x_tbook = 433
        <Description("application/x-lotusscreencam;.scm")> application_x_lotusscreencam = 434
        <Description("text/x-script.guile;.scm")> text_x_script_guile = 435
        <Description("text/x-script.scheme;.scm")> text_x_script_scheme = 436
        <Description("video/x-scm;.scm")> video_x_scm = 437
        <Description("application/sdp;.sdp")> application_sdp = 439
        <Description("application/x-sdp;.sdp")> application_x_sdp = 440
        <Description("application/sounder;.sdr")> application_sounder = 441
        <Description("application/sea;.sea")> application_sea = 442
        <Description("application/x-sea;.sea")> application_x_sea = 443
        <Description("application/set;.set")> application_set = 444
        <Description("text/sgml;.sgm")> text_sgml = 445
        <Description("text/x-sgml;.sgm")> text_x_sgml = 446
        <Description("application/x-sh;.sh")> application_x_sh = 450
        <Description("application/x-shar;.sh")> application_x_shar = 451
        <Description("text/x-script.sh;.sh")> text_x_script_sh = 452
        <Description("text/x-server-parsed-html;.shtml")> text_x_server_parsed_html = 456
        <Description("audio/x-psid;.sid")> audio_x_psid = 457
        <Description("application/x-sit;.sit")> application_x_sit = 458
        <Description("application/x-stuffit;.sit")> application_x_stuffit = 459
        <Description("application/x-koan;.skd")> application_x_koan = 460
        <Description("application/x-seelogo;.sl")> application_x_seelogo = 464
        <Description("application/smil;.smi")> application_smil = 465
        <Description("audio/x-adpcm;.snd")> audio_x_adpcm = 468
        <Description("application/solids;.sol")> application_solids = 469
        <Description("application/x-pkcs7-certificates;.spc")> application_x_pkcs7_certificates = 470
        <Description("text/x-speech;.spc")> text_x_speech = 471
        <Description("application/futuresplash;.spl")> application_futuresplash = 472
        <Description("application/x-sprite;.spr")> application_x_sprite = 473
        <Description("application/x-wais-source;.src")> application_x_wais_source = 475
        <Description("application/streamingmedia;.ssm")> application_streamingmedia = 477
        <Description("application/vnd.ms-pki.certstore;.sst")> application_vnd_ms_pki_certstore = 478
        <Description("application/step;.step")> application_step = 479
        <Description("application/sla;.stl")> application_sla = 480
        <Description("application/vnd.ms-pki.stl;.stl")> application_vnd_ms_pki_stl = 481
        <Description("application/x-navistyle;.stl")> application_x_navistyle = 482
        <Description("application/x-sv4cpio;.sv4cpio")> application_x_sv4cpio = 484
        <Description("application/x-sv4crc;.sv4crc")> application_x_sv4crc = 485
        <Description("application/x-world;.svr")> application_x_world = 488
        <Description("x-world/x-svr;.svr")> x_world_x_svr = 489
        <Description("application/x-shockwave-flash;.swf")> application_x_shockwave_flash = 490
        <Description("application/x-tar;.tar")> application_x_tar = 493
        <Description("application/toolbook;.tbk")> application_toolbook = 494
        <Description("application/x-tcl;.tcl")> application_x_tcl = 496
        <Description("text/x-script.tcl;.tcl")> text_x_script_tcl = 497
        <Description("text/x-script.tcsh;.tcsh")> text_x_script_tcsh = 498
        <Description("application/x-tex;.tex")> application_x_tex = 499
        <Description("application/x-texinfo;.texi")> application_x_texinfo = 500
        <Description("application/plain;.text")> application_plain = 502
        <Description("application/gnutar;.tgz")> application_gnutar = 504
        <Description("image/tiff;.tif")> image_tiff = 506
        <Description("image/x-tiff;.tif")> image_x_tiff = 507
        <Description("audio/tsp-audio;.tsi")> audio_tsp_audio = 511
        <Description("application/dsptype;.tsp")> application_dsptype = 512
        <Description("audio/tsplayer;.tsp")> audio_tsplayer = 513
        <Description("text/tab-separated-values;.tsv")> text_tab_separated_values = 514
        <Description("text/x-uil;.uil")> text_x_uil = 517
        <Description("text/uri-list;.uni")> text_uri_list = 518
        <Description("application/i-deas;.unv")> application_i_deas = 520
        <Description("application/x-ustar;.ustar")> application_x_ustar = 523
        <Description("multipart/x-ustar;.ustar")> multipart_x_ustar = 524
        <Description("text/x-uuencode;.uu")> text_x_uuencode = 526
        <Description("application/x-cdlink;.vcd")> application_x_cdlink = 528
        <Description("text/x-vcalendar;.vcs")> text_x_vcalendar = 529
        <Description("application/vda;.vda")> application_vda = 530
        <Description("video/vdo;.vdo")> video_vdo = 531
        <Description("application/groupwise;.vew")> application_groupwise = 532
        <Description("video/vivo;.viv")> video_vivo = 533
        <Description("video/vnd.vivo;.viv")> video_vnd_vivo = 534
        <Description("application/vocaltec-media-desc;.vmd")> application_vocaltec_media_desc = 537
        <Description("application/vocaltec-media-file;.vmf")> application_vocaltec_media_file = 538
        <Description("audio/voc;.voc")> audio_voc = 539
        <Description("audio/x-voc;.voc")> audio_x_voc = 540
        <Description("video/vosaic;.vos")> video_vosaic = 541
        <Description("audio/voxware;.vox")> audio_voxware = 542
        <Description("audio/x-twinvq-plugin;.vqe")> audio_x_twinvq_plugin = 543
        <Description("audio/x-twinvq;.vqf")> audio_x_twinvq = 544
        <Description("application/x-vrml;.vrml")> application_x_vrml = 546
        <Description("model/vrml;.vrml")> model_vrml = 547
        <Description("x-world/x-vrml;.vrml")> x_world_x_vrml = 548
        <Description("x-world/x-vrt;.vrt")> x_world_x_vrt = 549
        <Description("application/x-visio;.vsd")> application_x_visio = 550
        <Description("application/wordperfect6.0;.w60")> application_wordperfect6_0 = 553
        <Description("application/wordperfect6.1;.w61")> application_wordperfect6_1 = 554
        <Description("audio/wav;.wav")> audio_wav = 556
        <Description("audio/x-wav;.wav")> audio_x_wav = 557
        <Description("application/x-qpro;.wb1")> application_x_qpro = 558
        <Description("image/vnd.wap.wbmp;.wbmp")> image_vnd_wap_wbmp = 559
        <Description("application/vnd.xara;.web")> application_vnd_xara = 560
        <Description("application/x-123;.wk1")> application_x_123 = 562
        <Description("windows/metafile;.wmf")> windows_metafile = 563
        <Description("text/vnd.wap.wml;.wml")> text_vnd_wap_wml = 564
        <Description("application/vnd.wap.wmlc;.wmlc")> application_vnd_wap_wmlc = 565
        <Description("text/vnd.wap.wmlscript;.wmls")> text_vnd_wap_wmlscript = 566
        <Description("application/vnd.wap.wmlscriptc;.wmlsc")> application_vnd_wap_wmlscriptc = 567
        <Description("application/wordperfect;.wp")> application_wordperfect = 569
        <Description("application/x-wpwin;.wpd")> application_x_wpwin = 574
        <Description("application/x-lotus;.wq1")> application_x_lotus = 575
        <Description("application/mswrite;.wri")> application_mswrite = 576
        <Description("application/x-wri;.wri")> application_x_wri = 577
        <Description("text/scriplet;.wsc")> text_scriplet = 583
        <Description("application/x-wintalk;.wtk")> application_x_wintalk = 585
        <Description("image/x-xbitmap;.xbm")> image_x_xbitmap = 586
        <Description("image/x-xbm;.xbm")> image_x_xbm = 587
        <Description("image/xbm;.xbm")> image_xbm = 588
        <Description("video/x-amt-demorun;.xdr")> video_x_amt_demorun = 589
        <Description("xgl/drawing;.xgz")> xgl_drawing = 590
        <Description("image/vnd.xiff;.xif")> image_vnd_xiff = 591
        <Description("application/excel;.xl")> application_excel = 592
        <Description("application/x-excel;.xla")> application_x_excel = 594
        <Description("application/x-msexcel;.xla")> application_x_msexcel = 595
        <Description("application/vnd.ms-excel;.xlb")> application_vnd_ms_excel = 597
        <Description("audio/xm;.xm")> audio_xm = 624
        <Description("application/xml;.xml")> application_xml = 625
        <Description("text/xml;.xml")> text_xml = 626
        <Description("xgl/movie;.xmz")> xgl_movie = 627
        <Description("application/x-vnd.ls-xpix;.xpix")> application_x_vnd_ls_xpix = 628
        <Description("image/xpm;.xpm")> image_xpm = 630
        <Description("video/x-amt-showrun;.xsr")> video_x_amt_showrun = 632
        <Description("image/x-xwd;.xwd")> image_x_xwd = 633
        <Description("image/x-xwindowdump;.xwd")> image_x_xwindowdump = 634
        <Description("application/x-compress;.z")> application_x_compress = 636
        <Description("application/x-zip-compressed;.zip")> application_x_zip_compressed = 639
        <Description("application/zip;.zip")> application_zip = 640
        <Description("multipart/x-zip;.zip")> multipart_x_zip = 641
        <Description("text/x-script.zsh;.zsh")> text_x_script_zsh = 643


    End Enum

#End Region

    Public Sub New()
        initVariable()
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="sLogfolder">Log 紀錄的路徑位置</param>
    ''' <param name="sTraceLogPrefix">Log檔案的前置字元</param>
    ''' <remarks></remarks>
    Public Sub New(ByVal sLogfolder As String, ByVal sTraceLogPrefix As String)
        mLogFolder = sLogfolder
        mTraceLogPrefix = sTraceLogPrefix
        initVariable()
    End Sub


    ''' <summary>
    ''' 主要參數初始化
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub initVariable()

        Dim execPath As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly.Location)

        If mLogFolder.Trim = "" Then
            mLogFolder = execPath.Trim("\") & "\Log\"
        Else
            mLogFolder = mLogFolder.Trim("\") & "\"
        End If

        If mCacheFolder.Trim = "" Then
            mCacheFolder = execPath.Trim("\") & "\Cache\"
        End If

        If mTraceLogPrefix.Trim() = "" Then
            mTraceLogPrefix = "trace"
        End If

        oLog = New LogHandler.clsLogger()

    End Sub

    ''' <summary>
    ''' 提供登入 Content Engine
    ''' </summary>
    ''' <param name="sUserID">使用者名稱</param>
    ''' <param name="sPwd">使用者密碼</param>
    ''' <param name="uri">Content Engine URI Ex: http://192.168.4.20:7001/wsi/FNCEWS40MTOM/ </param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function LogonCE(ByVal sUserID As String, ByVal sPwd As String, ByVal uri As String) As CEConnection
        Dim tmp As CEConnection
        tmp.aryObjectStoreName = New ArrayList
        Try
            'token = New UsernameToken(sUserID, sPwd, PasswordOption.SendPlainText)
            WriteTraceLogStart("Logon CE Process")

            WriteTraceLogStart("Create User Authentication")
            oCredentials = New Authentication.UsernameCredentials(sUserID, sPwd)
            ClientContext.SetProcessCredentials(oCredentials)
            WriteTraceLogEnd("Create User Authentication")

            WriteTraceLogStart("Connect to CE")
            connection = Factory.Connection.GetConnection(uri)
            WriteTraceLogEnd("Connect to CE")

            WriteTraceLogStart("Get Domain")
            domain = Factory.Domain.FetchInstance(connection, Nothing, Nothing)
            domainName = domain.Name
            WriteTraceLogEnd("Get Domain")

            WriteTraceLogStart("Get ObjectStoreSet")
            ost = domain.ObjectStores
            WriteTraceLogEnd("Get ObjectStoreSet")
            isConnected = True
            WriteTraceLogStart("Initial Variable")
            With tmp
                .conn = connection
                .domain = domain
                .domainName = domainName
                .objectStores = domain.ObjectStores
                Dim ie As IEnumerator = .objectStores.GetEnumerator()
                Dim os As IObjectStore
                While (ie.MoveNext())
                    os = CType(ie.Current, IObjectStore)
                    .aryObjectStoreName.Add(os.DisplayName)
                End While
            End With
            WriteTraceLogEnd("Initial Variable")
            WriteTraceLogEnd("Logon CE Process")

            Return tmp
        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            oLog.writeLine(mLogFolder, "ej", exFileNet.Message)
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            oLog.writeLine(mLogFolder, "ej", ex.ToString)
            Throw New Exception(ex.ToString)
        Finally

        End Try
    End Function

    ''' <summary>
    ''' 登出 Content Engine
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub LogoffCE()
        doLogoff(False)
    End Sub
    ''' <summary>
    ''' 登出 Content Engine
    ''' </summary>
    ''' <param name="CleanCache" >是否清空Cache中的檔案</param>
    ''' <remarks></remarks>
    Public Sub LogoffCE(ByVal CleanCache As Boolean)
        Try
            mCleanCache = CleanCache
            doLogoff(CleanCache)

        Catch ex As Exception
            oLog.writeLine(mLogFolder, "ej", ex.ToString)
            Throw New Exception(ex.ToString)

        End Try
    End Sub

    ''' <summary>
    ''' 實際把物件Nothing and 清除Cache中的檔案
    ''' </summary>
    ''' <param name="cleancache"></param>
    ''' <remarks></remarks>
    Private Sub doLogoff(ByVal cleancache As Boolean)
        Try
            WriteTraceLogStart("Logoff CE Process")
            domain = Nothing
            ost = Nothing
            connection = Nothing
            WriteTraceLogEnd("Logoff CE Process")
            If cleancache = True Then
                WriteTraceLogStart("Logoff Clear Cache")
                clearCache()
                WriteTraceLogEnd("Logoff Clear Cache")
            End If
        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            oLog.writeLine(mLogFolder, "ej", exFileNet.Message)
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            oLog.writeLine(mLogFolder, "ej", ex.ToString)
            Throw New Exception(ex.ToString)
        Finally
        End Try
    End Sub

    ''' <summary>
    ''' 建立 Content Engine中指定Object Store中的 Folder
    ''' </summary>
    ''' <param name="sObjectStoreName">Object Store 名稱 </param>
    ''' <param name="sPath">Folder 所在路徑 </param>
    ''' <param name="sFolderName">Folder名稱</param>
    ''' <param name="sClassName">
    ''' Folder 指定的 Class ,當空白時會使用系統Class "Folder" 作為預設的Class
    ''' </param>
    ''' <returns>IFolder物件</returns>
    ''' <remarks></remarks>
    Public Function CreateFolder(ByVal sObjectStoreName As String, _
                                 ByVal sPath As String, _
                                 ByVal sFolderName As String, _
                                 ByVal sClassName As String) As IFolder

        Try
            Return doCreateFolder(sObjectStoreName, sPath, sFolderName, sClassName, Nothing)

        Catch ex As Exception
            oLog.writeLine(mLogFolder, "ej", ex.ToString)
            Throw New Exception(ex.ToString)
        End Try

    End Function

    ''' <summary>
    ''' 建立 Content Engine中指定Object Store中的 Folder
    ''' </summary>
    ''' <param name="sObjectStoreName">Object Store 名稱 </param>
    ''' <param name="sPath">Folder 所在路徑 </param>
    ''' <param name="sFolderName">Folder名稱</param>
    ''' <param name="sClassName">Folder 指定的 Class ,當空白時會使用系統Class "Folder" 作為預設的Class</param>
    ''' <param name="properties" >Folder 屬性值 </param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function CreateFolder(ByVal sObjectStoreName As String, _
                                 ByVal sPath As String, _
                                 ByVal sFolderName As String, _
                                 ByVal sClassName As String, _
                                 ByVal properties() As PropertyInfo) As IFolder
        Try
            Return doCreateFolder(sObjectStoreName, sPath, sFolderName, sClassName, properties)

        Catch ex As Exception
            oLog.writeLine(mLogFolder, "ej", ex.ToString)
            Throw New Exception(ex.ToString)
        End Try

    End Function


    ''' <summary>
    ''' 建立 Content Engine中指定Object Store中的 Folder
    ''' </summary>
    ''' <param name="sObjectStoreName">Object Store 名稱 </param>
    ''' <param name="sPath">Folder 所在路徑 </param>
    ''' <param name="sFolderName">Folder名稱</param>
    ''' <param name="sClassName">Folder 指定的 Class ,當空白時會使用系統Class "Folder" 作為預設的Class</param>
    ''' <param name="properties" >Folder 屬性值 </param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function doCreateFolder(ByVal sObjectStoreName As String, _
                                 ByVal sPath As String, _
                                 ByVal sFolderName As String, _
                                 ByVal sClassName As String, _
                                 ByVal properties() As PropertyInfo) As IFolder
        Dim strRt As String = String.Empty
        Dim oObjectStore As IObjectStore = Nothing
        Dim oFolder As IFolder = Nothing
        Dim oParentFolder As IFolder = Nothing
        Try
            WriteTraceLogStart("Fetch Object Store")
            oObjectStore = FetchObjectStore(sObjectStoreName)
            WriteTraceLogEnd("Fetch Object Store")

            'Need To Test : 確認沒有Path的情形

            '取的Parent Folder 的 IFolder物件
            WriteTraceLogStart("Fetch Parent Folder")
            oParentFolder = Factory.Folder.FetchInstance(oObjectStore, sPath, Nothing)
            WriteTraceLogEnd("Fetch Parent Folder")

            WriteTraceLogStart("Create Folder")
            If (sClassName.Equals("")) Then
                '當Folder的Class為空白時,預設使用 "Folder"
                oFolder = Factory.Folder.CreateInstance(oObjectStore, "Folder")
            Else
                oFolder = Factory.Folder.CreateInstance(oObjectStore, sClassName)
            End If
            oFolder.FolderName = sFolderName
            oFolder.Parent = oParentFolder

            If Not properties Is Nothing Then
                For i As Integer = properties.GetLowerBound(0) To properties.GetUpperBound(0)
                    With properties(i)
                        oFolder.Properties(.PropertyName) = .PropertyValue
                    End With
                Next
            End If

            oFolder.Save(RefreshMode.REFRESH)

            WriteTraceLogEnd("Create Folder")

            Return oFolder
        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            Throw New Exception(ex.ToString)
        End Try

    End Function

#Region "Create Doc "





    ''' <summary>
    ''' 在Content Engine 中建立文件
    ''' </summary>
    ''' <param name="sObjectStore" >Content 儲存的 ObjectStore</param>
    ''' <param name="FileName">檔案名稱(全路徑)</param>
    ''' <param name="withContent">是否包含實體檔案</param>
    ''' <param name="eumMimeType">MIME Type</param>
    ''' <param name="docTitle">Title</param>
    ''' <param name="fileInFolder" >是否要存入Folder之中</param>
    ''' <param name="folderName" >Folder名稱,空白時為 "/" </param>
    ''' <returns>IDocument 物件</returns>
    ''' <remarks></remarks>
    Public Function CreateDoc(ByVal sObjectStore As String, _
                              ByVal className As String, _
                              ByVal fileName As String, _
                              ByVal withContent As Boolean, _
                              ByVal eumMimeType As MimeType, _
                              ByVal docTitle As String, _
                              ByVal fileInFolder As Boolean, _
                              ByVal folderName As String, _
                              ByVal isCheckIn As Boolean, _
                              ByVal eumCheckInType As CheckinType) As IDocument
        Dim oDoc As IDocument = Nothing
        Try
            oDoc = doCreateDoc(sObjectStore, fileName, withContent, eumMimeType, docTitle, fileInFolder, folderName, Nothing, className, isCheckIn, eumCheckInType)
            Return oDoc

        Catch ex As Exception
            oLog.writeLine(mLogFolder, "ej", ex.ToString)
            Throw New Exception(ex.ToString)

        End Try

    End Function


    ''' <summary>
    ''' 在Content Engine 中建立文件
    ''' </summary>
    ''' <param name="sObjectStore" >Content 儲存的 ObjectStore</param>
    ''' <param name="withContent">是否包含實體檔案</param>
    ''' <param name="FileName">檔案名稱(全路徑)</param>
    ''' <param name="eumMimeType">MIME Type</param>
    ''' <param name="docTitle">Title</param>
    ''' <param name="fileInFolder" >是否要存入Folder之中</param>
    ''' <param name="folderName" >Folder名稱,空白時為 "/" </param>
    ''' <param name="properties" >Document 屬性值 </param>
    ''' <returns>IDocument 物件</returns>
    ''' <remarks></remarks>
    Public Function CreateDoc(ByVal sObjectStore As String, _
                          ByVal className As String, _
                          ByVal fileName As String, _
                          ByVal withContent As Boolean, _
                          ByVal eumMimeType As MimeType, _
                          ByVal docTitle As String, _
                          ByVal fileInFolder As Boolean, _
                          ByVal folderName As String, _
                          ByVal properties() As PropertyInfo, _
                          ByVal isCheckIn As Boolean, _
                          ByVal eumCheckInType As CheckinType) As IDocument

        Dim oDoc As IDocument = Nothing
        Try
            oDoc = doCreateDoc(sObjectStore, fileName, withContent, eumMimeType, docTitle, fileInFolder, folderName, properties, className, isCheckIn, eumCheckInType)
            Return oDoc
        Catch ex As Exception
            oLog.writeLine(mLogFolder, "ej", ex.ToString)
            Throw New Exception(ex.ToString)

        End Try


    End Function


    ''' <summary>
    ''' 在Content Engine 中建立文件
    ''' </summary>
    ''' <param name="sObjectStore" >Content 儲存的 ObjectStore</param>
    ''' <param name="withContent">是否包含實體檔案</param>
    ''' <param name="FileName">檔案名稱(全路徑)</param>
    ''' <param name="eumMimeType">MIME Type</param>
    ''' <param name="docTitle">Title</param>
    ''' <param name="fileInFolder" >是否要存入Folder之中</param>
    ''' <param name="folderName" >Folder名稱,空白時為 "/" </param>
    ''' <param name="properties" >Document 屬性值 </param>
    ''' <returns>IDocument 物件</returns>
    ''' <remarks></remarks>
    Private Function doCreateDoc(ByVal sObjectStore As String, _
                              ByVal fileName As String, _
                              ByVal withContent As Boolean, _
                              ByVal eumMimeType As MimeType, _
                              ByVal docTitle As String, _
                              ByVal fileInFolder As Boolean, _
                              ByVal folderName As String, _
                              ByVal properties() As PropertyInfo, _
                              ByVal sClassName As String, _
                              ByVal isCheckIn As Boolean, _
                              ByVal eumCheckInType As CheckinType, _
                              Optional ByVal byteFile() As Byte = Nothing) As IDocument
        Dim oDoc As IDocument = Nothing
        Dim os As IObjectStore
        Dim oContentElementList As IContentElementList
        Dim oFolder As IFolder = Nothing
        Dim rcr As IReferentialContainmentRelationship = Nothing
        Try
            'Get Current ObjectStore to Create Doc
            WriteTraceLogStart("Fetch To ObjectStore " & sObjectStore)
            os = FetchObjectStore(sObjectStore)
            WriteTraceLogEnd("Fetch To ObjectStore " & sObjectStore)

            WriteTraceLogStart("Create Document Instance")
            oDoc = Factory.Document.CreateInstance(os, sClassName)
            WriteTraceLogEnd("Create Document Instance")

            oDoc.Properties("DocumentTitle") = docTitle

            doSetProperty(oDoc, properties)
            oDoc.MimeType = convertMIMEType(eumMimeType)
            If withContent = True Then
                WriteTraceLogStart("寫入檔案內容")
                oContentElementList = CreateContentElementList(fileName)
                If Not (oContentElementList Is Nothing) Then
                    oDoc.ContentElements = oContentElementList
                End If
                WriteTraceLogEnd("寫入檔案內容")

            End If
            oDoc.Save(RefreshMode.REFRESH)

            If fileInFolder = True Then
                WriteTraceLogStart("File In Folder " & folderName)
                oFolder = Factory.Folder.FetchInstance(os, folderName, Nothing)
                rcr = oFolder.File(oDoc, AutoUniqueName.AUTO_UNIQUE, oDoc.Name, DefineSecurityParentage.DO_NOT_DEFINE_SECURITY_PARENTAGE)
                rcr.Save(RefreshMode.REFRESH)
                WriteTraceLogEnd("File In Folder " & folderName)

            End If

            If isCheckIn = True Then
                WriteTraceLogStart("Check In Doc ")
                oDoc.Checkin(AutoClassify.AUTO_CLASSIFY, eumCheckInType)
                oDoc.Save(RefreshMode.REFRESH)
                WriteTraceLogEnd("Check In Doc ")
            End If
            oDoc.Refresh()
            Return oDoc
        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            Throw New Exception(ex.ToString)
        Finally

        End Try


    End Function

    ''' <summary>
    ''' 建立 CreateContentElementList 物件
    ''' </summary>
    ''' <param name="sFileName"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function CreateContentElementList(ByVal sFileName As String) As IContentElementList
        Dim cel As IContentElementList = Nothing
        Dim ct As IContentTransfer
        Try
            WriteTraceLogStart("CreateContentElementList")
            If Not (createContentTransfer(sFileName) Is Nothing) Then
                cel = Factory.ContentElement.CreateList
                ct = createContentTransfer(sFileName)
                cel.Add(ct)
            End If
            WriteTraceLogEnd("CreateContentElementList")

            Return cel
        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            Throw New Exception(ex.ToString)
        End Try


    End Function

    ''' <summary>
    ''' 建立 Content Transfer 物件
    ''' </summary>
    ''' <param name="sFileName"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function createContentTransfer(ByVal sFileName As String) As IContentTransfer
        Dim ct As IContentTransfer = Nothing
        Dim fi As FileInfo = Nothing
        Dim s As Stream
        Try
            WriteTraceLogStart("createContentTransfer")

            fi = New FileInfo(sFileName)
            If Not (ReadContentFromFile(sFileName) Is Nothing) Then

                ct = Factory.ContentTransfer.CreateInstance()
                s = New MemoryStream(ReadContentFromFile(sFileName))
                ct.SetCaptureSource(s)
                ct.RetrievalName = fi.Name
            End If
            WriteTraceLogEnd("createContentTransfer")

            Return ct
        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            Throw New Exception(ex.ToString)
        End Try

    End Function

    ''' <summary>
    ''' 讀取檔案為Binary Data
    ''' </summary>
    ''' <param name="sFileName"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ReadContentFromFile(ByVal sFileName As String) As Byte()
        Dim fi As New FileInfo(sFileName)
        Dim numBytes As Long
        Dim buffer As Byte() = Nothing
        Dim fs As FileStream
        Dim br As BinaryReader
        Try
            WriteTraceLogStart("將實體檔案讀入Memory")

            numBytes = fi.Length

            If numBytes > 0 Then
                fs = New FileStream(sFileName, FileMode.Open, FileAccess.Read)
                br = New BinaryReader(fs)
                buffer = br.ReadBytes(CType(numBytes, Integer))
                br.Close()
                fs.Close()

            End If
            WriteTraceLogEnd("將實體檔案讀入Memory")

            Return buffer
        Catch ex As Exception
            Throw New Exception(ex.ToString)
        End Try

    End Function

#End Region


    ''' <summary>
    ''' 設定 Document 屬性值
    ''' </summary>
    ''' <param name="oDoc"></param>
    ''' <param name="Properties"></param>
    ''' <remarks></remarks>
    Public Sub SetDocProperties(ByRef oDoc As IDocument, _
                                ByVal Properties() As PropertyInfo)
        Try
            doSetProperty(oDoc, Properties)
            oDoc.Save(RefreshMode.REFRESH)

        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            oLog.writeLine(mLogFolder, "ej", exFileNet.Message)
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            oLog.writeLine(mLogFolder, "ej", ex.ToString)
            Throw New Exception(ex.ToString)
        End Try

    End Sub

    ''' <summary>
    ''' 取得指定的屬性值
    ''' </summary>
    ''' <param name="oDoc"></param>
    ''' <param name="sPropName"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetDocProperty(ByVal oDoc As IDocument, ByVal sPropName As String) As Object
        Try
            If oDoc.Properties.IsPropertyPresent(sPropName) = False Then
                Throw New Exception("Property " & sPropName & " Not Exist ")
            End If
            Return oDoc.Properties(sPropName)
        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            oLog.writeLine(mLogFolder, "ej", exFileNet.Message)
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            oLog.writeLine(mLogFolder, "ej", ex.ToString)
            Throw New Exception(ex.ToString)
        End Try
    End Function


    ''' <summary>
    ''' 實際設定 Document 屬性
    ''' </summary>
    ''' <param name="oDoc"></param>
    ''' <param name="Properties"></param>
    ''' <remarks></remarks>
    Private Sub doSetProperty(ByRef oDoc As IDocument, _
                                     ByVal Properties() As PropertyInfo)
        Try
            WriteTraceLogStart("Set Doc Property")
            If Not Properties Is Nothing Then
                For i As Integer = Properties.GetLowerBound(0) To Properties.GetUpperBound(0)
                    With Properties(i)
                        oDoc.Properties(.PropertyName) = .PropertyValue
                    End With
                Next
            End If

            WriteTraceLogEnd("Set Doc Property")
        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            Throw New Exception(ex.ToString)
        End Try
    End Sub


    ''' <summary>
    ''' 簽入 Document
    ''' </summary>
    ''' <param name="oDoc"></param>
    ''' <param name="oType"></param>
    ''' <remarks></remarks>
    Public Sub CheckInDoc(ByRef oDoc As IDocument, ByVal oType As CheckinType)
        Try
            WriteTraceLogStart("Check In Doc")
            oDoc.Checkin(AutoClassify.AUTO_CLASSIFY, oType)
            oDoc.Save(RefreshMode.REFRESH)
            oDoc.Refresh()
            WriteTraceLogEnd("Check In Doc")
        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            oLog.writeLine(mLogFolder, "ej", exFileNet.Message)
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            oLog.writeLine(mLogFolder, "ej", ex.ToString)
            Throw New Exception(ex.ToString)
        End Try

    End Sub

    ''' <summary>
    ''' 簽出 Document
    ''' </summary>
    ''' <param name="oDoc"></param>
    ''' <remarks></remarks>
    Public Sub CheckOutDoc(ByRef oDoc As IDocument)
        Try
            oDoc.Checkout(Nothing, Nothing, Nothing, Nothing)
        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            oLog.writeLine(mLogFolder, "ej", exFileNet.Message)
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            oLog.writeLine(mLogFolder, "ej", ex.ToString)
            Throw New Exception(ex.ToString)
        End Try
    End Sub

    ''' <summary>
    ''' 取消簽出
    ''' </summary>
    ''' <param name="oDoc"></param>
    ''' <remarks></remarks>
    Public Sub CancelCheckOut(ByRef oDoc As IDocument)
        Try
            oDoc.CancelCheckout()
        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            oLog.writeLine(mLogFolder, "ej", exFileNet.Message)
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            oLog.writeLine(mLogFolder, "ej", ex.ToString)
            Throw New Exception(ex.ToString)
        End Try

    End Sub

    ''' <summary>
    ''' 將指定的文件刪除
    ''' </summary>
    ''' <param name="oDoc">Document</param>
    ''' <remarks></remarks>
    Public Sub DeleteDoc(ByRef oDoc As IDocument)
        Try
            WriteTraceLogStart("Delete Doc")
            oDoc.Delete()
            oDoc.Save(RefreshMode.NO_REFRESH)
            WriteTraceLogEnd("Delete Doc")
        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            oLog.writeLine(mLogFolder, "ej", exFileNet.Message)
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            oLog.writeLine(mLogFolder, "ej", ex.ToString)
            Throw New Exception(ex.ToString)
        End Try


    End Sub



    ''' <summary>
    ''' 傳入完整查詢語法,回傳Doc 相關資訊的 DataTable
    ''' </summary>
    ''' <param name="sObjectStoreName">Object Store Name</param>
    ''' <param name="sQuerySQL">完整SQL語法 select [field_list] from [doc_class] where ....</param>
    ''' <returns>data table </returns>
    ''' <remarks></remarks>
    Public Function GetDocList(ByVal sObjectStoreName As String, _
                               ByVal sQuerySQL As String) As DataTable

        Dim ss As SearchScope
        Dim sq As SearchSQL
        Dim rrs As IRepositoryRowSet
        Dim dt As New DataTable
        Dim dc As DataColumn
        Dim row() As String = Nothing
        Dim os As IObjectStore
        Dim firstpass As Boolean = True
        Dim table As New DataTable
        Dim ie As IEnumerator
        Dim rr As IRepositoryRow
        Dim aryPropNames As ArrayList

        Try
            Dim pos As Integer = sQuerySQL.ToLower.IndexOf("from")
            sQuerySQL = sQuerySQL.Substring(0, pos) & " , iscurrentversion as CurrVer " & " from " & sQuerySQL.Substring(pos + 4)
            os = FetchObjectStore(sObjectStoreName)
            WriteTraceLogStart("Create Query SQL")
            ss = New SearchScope(os)
            sq = New SearchSQL
            sq.SetQueryString(sQuerySQL)
            WriteTraceLogEnd("Create Query SQL")

            WriteTraceLogStart("Create Fetch Doc")
            rrs = ss.FetchRows(sq, Nothing, Nothing, Nothing)
            ie = rrs.GetEnumerator()
            WriteTraceLogEnd("Create Fetch Doc")

            WriteTraceLogStart("Create DocInfo Table")
            While ie.MoveNext
                rr = ie.Current
                If firstpass Then
                    aryPropNames = GetPropertyNames(rr)
                    For i As Integer = 0 To aryPropNames.Count - 1
                        dc = New DataColumn
                        dc.ColumnName = aryPropNames(i)
                        dt.Columns.Add(dc)
                    Next
                    firstpass = False
                End If
                row = GetPropertyValue(rr)
                dt.Rows.Add(row)
            End While

            Dim returnDT As DataTable = dt.Clone
            For Each dr As DataRow In dt.Rows
                If dr("CurrVer") = True Then
                    returnDT.ImportRow(dr)
                End If
            Next

            WriteTraceLogEnd("Create DocInfo Table")
            Return returnDT
        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            oLog.writeLine(mLogFolder, "ej", exFileNet.Message)
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            oLog.writeLine(mLogFolder, "ej", ex.ToString)
            Throw New Exception(ex.ToString)
        End Try

    End Function


    ''' <summary>
    ''' 傳入對應的object store name, Doc ID 取得 IDocument 物件
    ''' </summary>
    ''' <param name="sObjectStoreName">Object Store Name</param>
    ''' <param name="DocID">"id" property of document  </param>
    ''' <returns>IDocument</returns>
    ''' <remarks></remarks>
    Public Function GetIDocument(ByVal sObjectStoreName As String, ByVal DocID As String) As IDocument
        Dim oDoc As IDocument
        Try
            WriteTraceLogStart("Fetch Document By DocID : " & DocID)
            oDoc = FetchDocument(sObjectStoreName, DocID)
            WriteTraceLogEnd("Fetch Document By DocID : " & DocID)
            Return oDoc
        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            oLog.writeLine(mLogFolder, "ej", exFileNet.Message)
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            oLog.writeLine(mLogFolder, "ej", ex.ToString)
            Throw New Exception(ex.ToString)

        End Try

    End Function


    ''' <summary>
    ''' 傳入對應的object store name, Doc ID 取得文件內容,存在Cache中,回傳檔案路徑 
    ''' </summary>
    ''' <param name="sObjectStoreName">Object Store Name</param>
    ''' <param name="DocID">"id" property of document  </param>
    ''' <returns>Doc Full Path</returns>
    ''' <remarks></remarks>
    Public Function GetDocContentByOSName(ByVal sObjectStoreName As String, ByVal DocID As String) As String
        Dim os As IObjectStore = Nothing
        Dim sPath As String = ""
        Try
            os = FetchObjectStore(sObjectStoreName)
            sPath = doGetDocContent(os, DocID)
            Return sPath
        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            oLog.writeLine(mLogFolder, "ej", exFileNet.Message)
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            oLog.writeLine(mLogFolder, "ej", ex.ToString)
            Throw New Exception(ex.ToString)
        End Try

    End Function

    ''' <summary>
    ''' 傳入對應的object store 物件(iObjectStore), Doc ID 取得文件內容,存在Cache中,回傳檔案路徑
    ''' </summary>
    ''' <param name="oObjectStore">IOjectStore Object</param>
    ''' <param name="DocID">"id" property of document</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetDocContentByIOS(ByVal oObjectStore As IObjectStore, ByVal DocID As String) As String
        Dim sPath As String = ""
        Try
            sPath = doGetDocContent(oObjectStore, DocID)
            Return sPath
        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            oLog.writeLine(mLogFolder, "ej", exFileNet.Message)
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            oLog.writeLine(mLogFolder, "ej", ex.ToString)
            Throw New Exception(ex.ToString)
        End Try

    End Function


    ''' <summary>
    ''' 傳入 IDocument 物件取得文件內容,存在Cache中,回傳檔案路徑
    ''' </summary>
    ''' <param name="oDoc">IDocument Object</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetDocContentByIDoc(ByVal oDoc As IDocument) As String
        Dim sId As String = oDoc.Id.ToString
        Dim sPath As String
        Dim docFullPath As String = ""

        Try
            sPath = mCacheFolder.Trim("\") & "\" & sId
            docFullPath = WriteContentToFile(oDoc, sPath)
            'If System.IO.Directory.Exists(sPath) Then
            '    Try
            '        System.IO.Directory.Delete(sPath, True)
            '        System.IO.Directory.CreateDirectory(sPath)
            '    Catch ex As Exception

            '    End Try
            'Else
            '    System.IO.Directory.CreateDirectory(sPath)
            'End If
            'If oDoc.MimeType.ToLower.IndexOf("tif") >= 0 Then
            '    'docFullPath = WriteContentToFileForTiff(oDoc, sPath)
            '    docFullPath = WriteContentToFile(oDoc, sPath)
            'Else
            '    docFullPath = WriteContentToFileForOthers(oDoc, sPath)
            'End If
            Return docFullPath
        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            oLog.writeLine(mLogFolder, "ej", exFileNet.Message)
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            oLog.writeLine(mLogFolder, "ej", ex.ToString)
            Throw New Exception(ex.ToString)

        End Try

    End Function

    ''' <summary>
    ''' 實際取得文件內容,存在Cache中,回傳檔案路徑
    ''' </summary>
    ''' <param name="os"></param>
    ''' <param name="sID"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function doGetDocContent(ByVal os As IObjectStore, ByVal sID As String) As String
        Dim id As FileNet.Api.Util.Id
        Dim oDoc As IDocument
        Dim sPath As String = ""
        Dim docFullPath As String = ""
        Try
            WriteTraceLogStart("Get Doc Content ")

            id = New FileNet.Api.Util.Id(sID)
            oDoc = Factory.Document.FetchInstance(os, id, Nothing)
            sPath = mCacheFolder.Trim("\") & "\" & sID
            If System.IO.Directory.Exists(sPath) = False Then
                System.IO.Directory.CreateDirectory(sPath)
            End If

            docFullPath = WriteContentToFile(oDoc, sPath)

            WriteTraceLogEnd("Get Doc Content ")

            'If oDoc.MimeType.ToLower.IndexOf("tif") >= 0 Then
            '    docFullPath = WriteContentToFileForTiff(oDoc, sPath)
            'Else
            '    docFullPath = WriteContentToFileForOthers(oDoc, sPath)
            'End If
            ''docFullPath = System.IO.Path.Combine(sPath, oDoc.Name)
            'If System.IO.Path.GetExtension(docFullPath) = "" Then
            '    Dim extFile As String = Me.convertMIMEtoExtFileName(oDoc.MimeType)
            '    Dim NewFullPath As String = System.IO.Path.ChangeExtension(docFullPath, extFile)
            '    Dim oFileInfo As New System.IO.FileInfo(docFullPath)
            '    System.IO.File.Delete(NewFullPath)
            '    oFileInfo.MoveTo(NewFullPath)
            '    docFullPath = NewFullPath
            'End If
            Return docFullPath
        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            Throw New Exception(ex.ToString)
        End Try

    End Function


    ''' <summary>
    ''' 傳入對應的object store name, Doc ID 取得文件內容,回傳Byte()
    ''' </summary>
    ''' <param name="sObjectStoreName">Object Store Name</param>
    ''' <param name="DocID">"id" property of document  </param>
    ''' <returns>Binary Data Byte()</returns>
    ''' <remarks></remarks>
    Public Function GetDocBinary(ByVal sObjectStoreName As String, ByVal DocID As String) As Byte()
        Dim os As IObjectStore = Nothing
        Dim oDoc As IDocument
        Dim s As System.IO.Stream
        Dim data As Byte()
        Try
            os = FetchObjectStore(sObjectStoreName)
            oDoc = Factory.Document.FetchInstance(os, DocID, Nothing)
            s = oDoc.AccessContentStream(0)
            ReDim data(s.Length)
            s.Read(data, 0, data.Length)
            s.Close()
            Return data
        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            oLog.writeLine(mLogFolder, "ej", exFileNet.Message)
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            oLog.writeLine(mLogFolder, "ej", ex.ToString)
            Throw New Exception(ex.ToString)
        End Try
    End Function

    Private Function WriteContentToFile(ByVal doc As IDocument, ByVal path As String) As String
        Dim sExt As String = convertMIMEtoExtFileName(doc.MimeType)
        Dim filename As String = System.IO.Path.ChangeExtension(doc.Name, sExt)
        Dim outFile As String = System.IO.Path.Combine(path, filename)
        If System.IO.File.Exists(outFile) Then
            Return outFile
        End If
        Dim fs As New FileStream(outFile, FileMode.CreateNew)
        Dim bw As New BinaryWriter(fs)
        Dim s As System.IO.Stream = doc.AccessContentStream(0)
        Dim data As Byte()

        ReDim data(s.Length)
        Try
            s.Read(data, 0, data.Length)
            s.Close()
            bw.Write(data)
            bw.Close()
            fs.Close()
            Return outFile
        Catch ex As Exception
            oLog.writeLine(mLogFolder, "ej", ex.ToString)
            Throw New Exception(ex.ToString)
        Finally
            s.Dispose()
            s = Nothing
            bw = Nothing
            fs.Dispose()
            fs = Nothing
        End Try

    End Function

#Region "for test"
    '''' <summary>
    '''' Reads the content from Document's ContentStream and copies it to a file on a file system.
    '''' </summary>
    '''' <param name="doc">current Document object </param>
    '''' <param name="path">Full Path with FileName</param>
    '''' <remarks></remarks>
    'Private Function WriteContentToFileForTiff(ByVal doc As IDocument, ByVal path As String) As String
    '    'To do Check doc.name 是否包含附檔名
    '    Dim tmpWorkIngPath As String = path & "\" & Now.ToString("yyyyMMddHHmmss")
    '    Dim sExt As String = convertMIMEtoExtFileName(doc.MimeType)
    '    Dim filename As String = System.IO.Path.ChangeExtension(doc.Name, sExt)
    '    Dim outFile As String = System.IO.Path.Combine(path, filename)

    '    If System.IO.File.Exists(outFile) Then
    '        Return outFile
    '    End If

    '    Dim tmpFile As String = System.IO.Path.Combine(tmpWorkIngPath, "tmp" & filename)

    '    If System.IO.Directory.Exists(tmpWorkIngPath) = False Then
    '        System.IO.Directory.CreateDirectory(tmpWorkIngPath)
    '    End If

    '    Dim fs As New FileStream(tmpFile, FileMode.CreateNew)
    '    Dim bw As New BinaryWriter(fs)
    '    Dim s As System.IO.Stream = doc.AccessContentStream(0)
    '    Dim data As Byte()
    '    Try


    '        ReDim data(s.Length)
    '        s.Read(data, 0, data.Length)
    '        s.Close()
    '        bw.Write(data)
    '        bw.Close()
    '        fs.Close()
    '        'Dim oMerge As New TiffManager.util(tmpFile)
    '        'oMerge.TempWorkingDir = tmpWorkIngPath
    '        'oMerge.ConvertTiffFormat(tmpWorkIngPath & "\tmp.tif", Imaging.EncoderValue.CompressionCCITT4)
    '        'oMerge.Dispose()
    '        ConvertTiffFormat(tmpFile, tmpWorkIngPath & "\tmp.tif", _
    '                          tmpWorkIngPath, Imaging.EncoderValue.CompressionCCITT4)

    '        System.IO.File.Copy(tmpWorkIngPath & "\tmp.tif", outFile)
    '        Dim sFile() As String = System.IO.Directory.GetFiles(tmpWorkIngPath)
    '        For i As Integer = sFile.GetLowerBound(0) To sFile.GetUpperBound(0)
    '            Try
    '                System.IO.File.Delete(sFile(i))
    '            Catch ex As Exception

    '            End Try
    '        Next
    '        Try
    '            System.IO.Directory.Delete(tmpWorkIngPath, True)
    '        Catch ex As Exception

    '        End Try
    '        Return outFile
    '    Catch ex As Exception
    '        s.Close()
    '        bw.Close()
    '        fs.Close()
    '        Throw New Exception(ex.ToString)
    '    Finally
    '        s.Dispose()
    '        s = Nothing
    '        bw = Nothing
    '        fs.Dispose()
    '        fs = Nothing
    '    End Try


    'End Function

    'Private Function WriteContentToFileForOthers(ByVal doc As IDocument, ByVal path As String) As String
    '    'To do Check doc.name 是否包含附檔名
    '    Dim filename As String = System.IO.Path.ChangeExtension(doc.Name, convertMIMEtoExtFileName(doc.MimeType))
    '    Dim file As String = System.IO.Path.Combine(path, filename)
    '    If System.IO.File.Exists(file) Then
    '        Return file
    '    End If
    '    Dim fs As New FileStream(file, FileMode.CreateNew)
    '    Dim bw As New BinaryWriter(fs)
    '    Dim s As System.IO.Stream = doc.AccessContentStream(0)
    '    Dim data As Byte()
    '    Try

    '        ReDim data(s.Length)
    '        s.Read(data, 0, data.Length)
    '        s.Close()
    '        bw.Write(data)
    '        bw.Close()
    '        fs.Close()
    '        Return file
    '    Catch ex As Exception
    '        s.Close()
    '        bw.Close()
    '        fs.Close()
    '        Throw New Exception(ex.ToString)
    '    Finally
    '        s.Dispose()
    '        s = Nothing
    '        bw = Nothing
    '        fs.Dispose()
    '        fs = Nothing
    '    End Try


    'End Function
#End Region



    ''' <summary>
    ''' 傳入IRepositoryRow rr 取出所有 Property ,作為DataTable的 Column
    ''' </summary>
    ''' <returns>回傳Property Name 的ArrayList</returns>
    ''' <remarks></remarks>
    Private Function GetPropertyNames(ByVal rr As IRepositoryRow) As ArrayList

        Try
            Dim names As New ArrayList
            Dim prop As IProperties = rr.Properties
            Dim ie As IEnumerator = prop.GetEnumerator
            Dim p As IProperty
            Dim name As String
            While ie.MoveNext
                p = CType(ie.Current, IProperty)
                name = p.GetPropertyName
                names.Add(name)
            End While
            Return names
        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            Throw New Exception(ex.ToString)
        End Try

    End Function

    ''' <summary>
    ''' 組成 Properties 的 DataRow
    ''' </summary>
    ''' <param name="rr"></param>
    '''<returns ></returns>
    ''' <remarks></remarks>
    Private Function GetPropertyValue(ByVal rr As IRepositoryRow) As String()
        Dim row() As String = Nothing
        Dim i As Integer = 0
        Try
            Dim prop As IProperties = rr.Properties
            Dim ie As IEnumerator = prop.GetEnumerator()
            While ie.MoveNext
                ReDim Preserve row(i)
                Dim p As IProperty = CType(ie.Current, IProperty)
                Dim value As Object = p.GetObjectValue
                If value Is Nothing Then
                    row(i) = ""
                ElseIf TypeOf (value) Is IEngineCollection Then
                    row(i) = "*"
                ElseIf TypeOf (value) Is String Then
                    row(i) = value.ToString
                ElseIf TypeOf (value) Is Boolean Then
                    row(i) = Boolean.Parse(value)
                ElseIf TypeOf (value) Is Integer Then
                    row(i) = Integer.Parse(value)
                ElseIf TypeOf (value) Is Double Then
                    row(i) = Double.Parse(value)
                ElseIf TypeOf (value) Is DateTime Then
                    row(i) = DateTime.Parse(value)
                Else
                    row(i) = value.ToString
                End If
                i = i + 1
            End While

            Return row
        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            Throw New Exception(ex.ToString)
        End Try
    End Function


    ''' <summary>
    ''' 取得指定的 Object Store 物件
    ''' </summary>
    ''' <param name="sObjectStoreName">Object Store Name</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function FetchObjectStore(ByVal sObjectStoreName As String) As IObjectStore
        Dim os As IObjectStore
        Try
            os = Factory.ObjectStore.FetchInstance(domain, sObjectStoreName, Nothing)
            Return os
        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            Throw New Exception(ex.ToString)
        Finally

        End Try

    End Function

    ''' <summary>
    ''' 取得指定的 IDocument
    ''' </summary>
    ''' <param name="sObjectStoreName">Object Store Name</param>
    ''' <param name="sId"> Document ID Property</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function FetchDocument(ByVal sObjectStoreName As String, ByVal sId As String) As IDocument
        Try
            Dim ID As New FileNet.Api.Util.Id(sId)
            Dim os As IObjectStore = FetchObjectStore(sObjectStoreName)
            Dim doc As IDocument = Factory.Document.FetchInstance(os, ID, Nothing)
            Return doc
        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            Throw New Exception(ex.ToString)
        End Try

    End Function


#Region "Write Trace Log"
    ''' <summary>
    ''' 記錄步驟的起始,根據步驟名稱的長度,補滿 40 byte,並加上 START 
    ''' </summary>
    ''' <param name="StepTxt">步驟名稱</param>
    ''' <remarks></remarks>
    Private Sub WriteTraceLogStart(ByVal StepTxt As String)
        If mTraceFlag = True Then
            oLog.writeLine(mLogFolder, mTraceLogPrefix, "[" & cPadRight(StepTxt, 40, " ") & "] - START ")
        End If
    End Sub


    ''' <summary>
    ''' 記錄步驟的起始,根據步驟名稱的長度,補滿 20 byte,並加上 END
    ''' </summary>
    ''' <param name="StepTxt"></param>
    ''' <remarks></remarks>
    Private Sub WriteTraceLogEnd(ByVal StepTxt As String)
        If mTraceFlag = True Then
            oLog.writeLine(mLogFolder, mTraceLogPrefix, "[" & cPadRight(StepTxt, 40, " ") & "] - END ")
        End If
    End Sub

#End Region

#Region "內部處理 Function"
    ''' <summary>
    ''' 透過定義的 enum 變數,將 enum 型態 轉出對應的 decription 
    ''' </summary>
    ''' <param name="eumMimeType"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function convertMIMEType(ByVal eumMimeType As MimeType) As String
        Dim sMime As String
        Dim sMIMEDesc As String
        Try
            sMime = [Enum].GetName(GetType(MimeType), eumMimeType)
            Dim oMimeInfo As Reflection.FieldInfo = GetType(MimeType).GetField(sMime)
            Dim attr As DescriptionAttribute = DirectCast(oMimeInfo.GetCustomAttributes(GetType(DescriptionAttribute), False)(0), DescriptionAttribute)
            sMIMEDesc = attr.Description.Split(";")(0)
            Return sMIMEDesc
        Catch ex As Exception
            Throw New Exception(ex.ToString)
        End Try
    End Function

    ''' <summary>
    ''' 傳入MIME Type ,回傳附檔名
    ''' </summary>
    ''' <param name="MIMEDesc">MIME Type 字串 Ex: "image/tiff" </param>
    ''' <returns>附檔名</returns>
    ''' <remarks></remarks>
    Public Function convertMIMEtoExtFileName(ByVal MIMEDesc As String) As String
        Dim sMime As String
        Dim aryMime() As String
        Dim sExtName As String = ""
        Try
            aryMime = [Enum].GetNames(GetType(MimeType))
            For i As Integer = aryMime.GetLowerBound(0) To aryMime.GetUpperBound(0)
                sMime = aryMime(i)
                Dim oMimeInfo As Reflection.FieldInfo = GetType(MimeType).GetField(sMime)
                Dim attr As DescriptionAttribute = DirectCast(oMimeInfo.GetCustomAttributes(GetType(DescriptionAttribute), False)(0), DescriptionAttribute)
                If attr.Description.Split(";")(0) = MIMEDesc Then
                    sExtName = attr.Description.Split(";")(1)
                    Exit For
                End If
            Next
            If sExtName <> "" Then
                Return sExtName
            Else
                Throw New Exception("mime type not define ")
            End If
        Catch ex As Exception
            Throw New Exception("mime type not define ")
        End Try

    End Function

    ''' <summary>
    ''' 向左補滿,如果Pad字元超過一個Byte;則會完整補滿,所以長度可能會超過欲補滿的總長度
    ''' </summary>
    ''' <param name="oriTxt"></param>
    ''' <param name="iTotalLen"></param>
    ''' <param name="sPadTxt"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function cPadLeft(ByVal oriTxt As String, _
                              ByVal iTotalLen As Integer, _
                              ByVal sPadTxt As String) As String

        Dim iOriLen As Integer
        Dim sResult As String = oriTxt
        iOriLen = System.Text.Encoding.Default.GetBytes(oriTxt).Length
        While True
            sResult = sPadTxt & sResult
            If System.Text.Encoding.Default.GetBytes(sResult).Length >= iTotalLen Then
                Exit While
            End If
        End While
        Return sResult

    End Function



    ''' <summary>
    ''' 向右補滿,如果Pad字元超過一個Byte;則會完整補滿,所以長度可能會超過欲補滿的總長度
    ''' </summary>
    ''' <param name="oriTxt"></param>
    ''' <param name="iTotalLen"></param>
    ''' <param name="sPadTxt"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function cPadRight(ByVal oriTxt As String, _
                              ByVal iTotalLen As Integer, _
                              ByVal sPadTxt As String) As String

        Dim iOriLen As Integer
        Dim sResult As String = oriTxt
        iOriLen = System.Text.Encoding.Default.GetBytes(oriTxt).Length
        While True
            sResult = sResult & sPadTxt
            If System.Text.Encoding.Default.GetBytes(sResult).Length >= iTotalLen Then
                Exit While
            End If
        End While
        Return sResult

    End Function
#End Region

    Protected Overrides Sub Finalize()
        'delete cache file
        clearCache()
        MyBase.Finalize()
    End Sub

    ''' <summary>
    ''' 將Cache Folder中的資料清除
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub clearCache()
        Dim aryDir() As String
        Dim aryFile() As String
        Try
            If mCleanCache = True Then
                aryDir = System.IO.Directory.GetDirectories(mCacheFolder)

                For i As Integer = aryDir.GetLowerBound(0) To aryDir.GetUpperBound(0)
                    Try
                        System.IO.Directory.Delete(aryDir(i), True)
                    Catch ex As Exception

                    End Try
                Next
                aryFile = System.IO.Directory.GetFiles(mCacheFolder)
                For i As Integer = aryFile.GetLowerBound(0) To aryFile.GetUpperBound(0)
                    Try
                        System.IO.File.Delete(aryFile(i))
                    Catch ex As Exception

                    End Try
                Next
            End If
        Catch ex As Exception
            'do nothing
        End Try

    End Sub

    ''' <summary>
    ''' For Test
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub FetchClassDefinition()
        Dim os As IObjectStore = FetchObjectStore("OBJST1")
        Dim o As FileNet.Api.Admin.IClassDefinition
        Dim oProps As Collection.IPropertyDefinitionList
        Dim oo As FileNet.Api.Admin.IPropertyDefinition

        o = Factory.ClassDefinition.FetchInstance(os, "GenericDSIMS", Nothing)
        oProps = o.PropertyDefinitions
        For i As Integer = 0 To oProps.Count
            oo = oProps.Item(i)
        Next
    End Sub

    ''' <summary>
    ''' 檢查folder是否存在
    ''' </summary>
    ''' <param name="osName">Object Store Name</param>
    ''' <param name="sfolder">Folder Name</param>
    ''' <returns>true / false</returns>
    ''' <remarks></remarks>
    Public Function CheckFolderExist(ByVal osName As String, ByVal sfolder As String) As Boolean
        Dim oFolder As FileNet.Api.Core.IFolder
        Dim os As FileNet.Api.Core.IObjectStore
        os = Me.FetchObjectStore(osName)
        Try
            oFolder = Factory.Folder.FetchInstance(os, sfolder, Nothing)
            Return True
        Catch exFileNet As FileNet.Api.Exception.EngineRuntimeException
            Throw New Exception(exFileNet.Message)
        Catch ex As Exception
            Throw New Exception(ex.ToString)
        End Try

    End Function


    Private Sub ConvertTiffFormat(ByVal curImageFileName As String, _
                                  ByVal strNewImageFileName As String, _
                                  ByVal _TempWorkingDir As String, _
                                  ByVal compressEncoder As EncoderValue)
        Dim arrSplited As New ArrayList
        arrSplited = SplitTiffImage(curImageFileName, _TempWorkingDir, compressEncoder)
        JoinTiffImages(arrSplited, strNewImageFileName, compressEncoder)
    End Sub

    Public Function SplitTiffImage(ByVal _ImageFileName As String, _
                                   ByVal outPutDirectory As String, _
                                   ByVal format As EncoderValue) As ArrayList
        Dim fileStartString As String = outPutDirectory & "\" & GetFileNameStartString(_ImageFileName)
        Dim splitedFileNames As ArrayList = New ArrayList()
        Dim _PageNumber As Integer
        Dim image As System.Drawing.Image

        Try
            image = Drawing.Image.FromFile(_ImageFileName)
            Dim objGuid As Guid = image.FrameDimensionsList(0)
            Dim objDimension As FrameDimension = New FrameDimension(objGuid)
            _PageNumber = image.GetFrameCount(objDimension)
            '//Saves every frame as a separate file.
            Dim enc As System.Drawing.Imaging.Encoder = System.Drawing.Imaging.Encoder.Compression
            Dim curFrame As Integer = 0
            For i As Integer = 0 To _PageNumber - 1
                image.SelectActiveFrame(objDimension, curFrame)
                Dim ep As EncoderParameters = New EncoderParameters(1)
                ep.Param(0) = New EncoderParameter(enc, CType(format, Long))
                Dim info As ImageCodecInfo = GetEncoderInfo("image/tiff")
                Dim filename As String = String.Format("{0}{1}.TIF", fileStartString, i.ToString())
                image.Save(filename, info, ep)
                splitedFileNames.Add(filename)
                curFrame = curFrame + 1
            Next

        Catch ex As Exception
            Throw ex
        End Try
        Return splitedFileNames
    End Function

    Private Sub JoinTiffImages(ByVal imageFiles As ArrayList, _
                           ByVal outFile As String, _
                           ByVal compressEncoder As EncoderValue)
        Try
            If imageFiles.Count = 1 Then
                File.Copy(imageFiles(0).ToString, outFile, True)
                Exit Sub
            End If

            Dim enc As System.Drawing.Imaging.Encoder
            enc = System.Drawing.Imaging.Encoder.SaveFlag

            Dim ep As EncoderParameters = New EncoderParameters(2)
            ep.Param(0) = New EncoderParameter(enc, CType(EncoderValue.MultiFrame, Long))
            ep.Param(1) = New EncoderParameter(System.Drawing.Imaging.Encoder.Compression, CType(compressEncoder, Long))
            Dim pages As Bitmap = Nothing
            Dim frame As Integer = 0
            Dim info As ImageCodecInfo = GetEncoderInfo("image/tiff")
            For Each strImageFile As String In imageFiles
                If frame = 0 Then
                    pages = CType(Image.FromFile(strImageFile), Bitmap)
                    pages.Save(outFile, info, ep)
                Else
                    ep.Param(0) = New EncoderParameter(enc, CType(EncoderValue.FrameDimensionPage, Long))
                    Dim bm As Bitmap = CType(Image.FromFile(strImageFile), Bitmap)
                    pages.SaveAdd(bm, ep)
                    bm.Dispose()
                End If
                If frame = imageFiles.Count - 1 Then
                    'flush and close.
                    ep.Param(0) = New EncoderParameter(enc, CType(EncoderValue.Flush, Long))
                    pages.SaveAdd(ep)
                End If
                frame = frame + 1
            Next


        Catch ex As Exception

        End Try
    End Sub


    Private Function GetEncoderInfo(ByVal mimeType As String) As ImageCodecInfo
        Dim encoders As ImageCodecInfo() = Nothing
        encoders = ImageCodecInfo.GetImageEncoders()
        For j As Integer = 0 To encoders.Length - 1
            If encoders(j).MimeType = mimeType Then
                Return encoders(j)
            End If
        Next
        Throw New Exception(mimeType + " mime type not found in ImageCodecInfo")
    End Function


    Private Function GetFileNameStartString(ByVal _ImageFileName As String) As String
        'c:\test\text
        Dim posDot As Integer = _ImageFileName.LastIndexOf(".")
        Dim posSlash As Integer = _ImageFileName.LastIndexOf("\")
        If posDot < posSlash Then
            Return _ImageFileName.Substring(posSlash + 1)
        Else
            Return _ImageFileName.Substring(posSlash + 1, posDot - posSlash - 1)
        End If

    End Function
End Class
